#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "terrain.h"

Case assignationCase(const char element);


void terrainInit (Terrain * pTerrain, const char *nomFichier)
{
	FILE *monFic =NULL;
	int i,j;
	int valret;
	char c;

	monFic=fopen(nomFichier,"r");
	if(monFic==NULL)
	{
		printf(" Erreur lors de l'ouverture du fichier terrain \n");
	}

	valret=fscanf(monFic,"%d %d\n",&(pTerrain->dimX),&(pTerrain->dimY));
	if(valret!=2)
	{
		printf("Erreur de Lecture du fichier terrain pour dimx ou dimy\n");
	}

	pTerrain->tabCases=(Case**)malloc(pTerrain->dimX*sizeof(Case *));
	for(i=0;i<pTerrain->dimX;i++)
	{
		pTerrain->tabCases[i]=(Case*)malloc(pTerrain->dimY*sizeof(Case));
	}

	for(i=0;i<pTerrain->dimY;i++)
	{
		for(j=0;j<pTerrain->dimX;j++)
		{
			fscanf(monFic,"%c ",&c);
			pTerrain->tabCases[j][i] = assignationCase(c);
		}
	}
	fclose(monFic);
}

Case assignationCase(const char element)
{
	char *listeElementsTerrain = "h#_";
	int i,lg;
	i = 0;

	lg=strlen(listeElementsTerrain);
	while(element != listeElementsTerrain[i])
	{
		assert(i < lg);
		i++;
	}
	return (Case)i;
}

void terrainLibere(Terrain * pTerrain)
{
	int i;
		for(i=0;i<pTerrain->dimX;i++)
	{
		free(pTerrain->tabCases[i]);
	}
	free(pTerrain->tabCases);
}

int terrainPositionValide(Terrain *pTerrain, int x, int y)
{
    return ((x<(pTerrain->dimX)) && (y<(pTerrain->dimY)) && (x>=0) && (y>=0) && (pTerrain->tabCases[x][y] != herbe ) && (pTerrain->tabCases[x][y] != terre ));
}

int terrainGetX(const Terrain * pTerrain)
{
	return pTerrain->dimX;
}

int terrainGetY(const Terrain * pTerrain)
{
	return pTerrain->dimY;
}



Case terrainGetCase(const Terrain * pTerrain, int x, int y)
{
	return pTerrain->tabCases[x][y];
}


void terrainSetX(Terrain * pTerrain, int x)
{
	pTerrain->dimX=x;
}




void terrainSetY(Terrain * pTerrain,int y)
{
	pTerrain->dimY=y;
}



void terrainSetCase(Terrain * pTerrain, int x, int y, Case c)
{
	pTerrain->tabCases[x][y]=c;
}

